package com.ruoyi.web.controller.manage;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.manage.domain.request.LoginRequest;
import com.ruoyi.manage.domain.response.LoginResponse;
import com.ruoyi.manage.service.IAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: wwy
 * @Date: 2020/12/29 14:57
 */
@Api("移动端登录")
@RestController
@RequestMapping("/api")
public class AppLoginController extends BaseController {
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private TokenService tokenService;

    /**
     *  app用户登录
     *  1.进行账号，密码用户验证
     *  2.生成token，进行返回
     * @return
     */
    @ApiOperation("门户端登录接口")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginRequest loginRequest){
        //生成token
        LoginUser loginUser = new LoginUser();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(loginRequest.getUsername());
        sysUser.setPassword("app");
        boolean login = appUserService.login(loginRequest,sysUser);
        loginUser.setUser(sysUser);
        LoginResponse loginResponse = new LoginResponse();
        if(login){
            //登录成功
            String token = tokenService.createToken(loginUser);
            loginResponse.setToken(token);
        }else{
            //登录失败
            throw new CustomException("账号或密码错误", HttpStatus.ERROR);
        }
        return AjaxResult.success(loginResponse);
    }
}
